﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.SessionState;
namespace cebao.Web.mapinfo
{
    /// <summary>
    /// GetMaps 的摘要说明
    /// </summary>
    public class GetMaps : IHttpHandler, IRequiresSessionState
    {

        StringBuilder result = new StringBuilder();
        StringBuilder sb = new StringBuilder();
        StringBuilder rechild = new StringBuilder();
        cebao.BLL.mapinfo bll = new BLL.mapinfo();
        public void ProcessRequest(HttpContext context)
        {
            string ac = "";
            if (null != context.Request.Form["action"])
            {//获取前台传来的值  
                ac = context.Request.Form["action"].ToString().Trim();
            }
            else if (null != context.Request.QueryString["action"])
            {
                ac = context.Request.QueryString["action"].ToString().Trim();
            }
            if (ac == "query")
                Query(context);//本省数据                 
            else if (ac == "add")
                add(context);
            else if (ac == "modify")
                modify(context);
            else if (ac == "delete")
                delete(context);
            else if (ac == "queryc")//本用户级别下的用户
                Querychild(context);           
            else if (ac == "querymy")
                Querymy(context);
      

        }
       
        public void Querychild(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            if (Web.Admin.myinfo.isLogin(context))
            {
                int level = Web.Admin.myinfo.getLevel(context);
                string uname, utruename, uprovince, ucity, uunit, ucounty,mlevel = "4,3,2,1",st;
                utruename = uname = uprovince = ucity = uunit = ucounty = "";
                if (level == -1) level = 3;
                string[] pcc = Web.Admin.myinfo.getPCC(context).Split(',');
                uname = utruename = st = "";
                //获取前台传来的值 
                if (null != context.Request.Form["search_type"])
                {//获取前台传来的值  
                    st = context.Request.Form["search_type"].ToString().Trim();
                }
                if (null != context.Request.Form["search_value"])
                {//获取前台传来的值  
                    uname = context.Request.Form["search_value"].ToString().Trim();
                }
                if (st == "username")
                {
                    utruename = uname;
                    uname = "";
                }  
                if (null != context.Request.Form["uprovince"])
                {
                    uprovince = context.Request.Form["uprovince"].ToString().Trim();
                }
                if (null != context.Request.Form["ucity"])
                {
                    ucity = context.Request.Form["ucity"].ToString().Trim();
                }
                if (null != context.Request.Form["ucounty"])
                {
                    ucounty = context.Request.Form["ucounty"].ToString().Trim();
                }
                if (null != context.Request.Form["mlevel"])
                {
                    mlevel = context.Request.Form["mlevel"].ToString().Trim();
                }
                int pageRows, page;
                pageRows = 10;
                page = 1;
                string order, sort, oderby; order = sort = oderby = "";
                if (null != context.Request.Form["rows"])
                {
                    pageRows = int.Parse(context.Request.Form["rows"].ToString().Trim());
                }
                if (null != context.Request.Form["page"])
                {
                    page = int.Parse(context.Request.Form["page"].ToString().Trim());
                }
                if (null != context.Request.Form["sort"])
                {
                    order = context.Request.Form["sort"].ToString().Trim();
                }
                if (null != context.Request.Form["order"])
                {
                    sort = context.Request.Form["order"].ToString().Trim();
                }
                StringBuilder strWhere = new StringBuilder();
                if (uname != "")
                {
                    strWhere.AppendFormat(" uname like '%{0}%' and ", uname);
                }
                if (utruename != "")
                {
                    strWhere.AppendFormat(" utruename like '%{0}%' and ", utruename);
                }
                if (level <= 3)
                    uprovince = pcc[0];
                if (level <= 2)
                {
                    ucity = pcc[1];
                }
                if (level <= 1)
                {
                    ucounty = pcc[2];
                }
                if (ucounty != "")
                {
                    strWhere.AppendFormat(" ucounty='{0}' and ", ucounty);
                }

                if (ucity != "")
                {
                    strWhere.AppendFormat(" ucity='{0}' and ", ucity);
                }

                if (uprovince != "")
                {
                    strWhere.AppendFormat(" uprovince='{0}' and ", uprovince);

                }
                if (mlevel != "")
                {
                    strWhere.AppendFormat(" mlevel in ({0}) and ", mlevel);

                }  
                
                //删除多余的and  
                int startindex = strWhere.ToString().LastIndexOf("and");//获取最后一个and的位置  
                if (startindex >= 0)
                {
                    strWhere.Remove(startindex, 3);//删除多余的and关键字  
                }
                if (sort != "" && order != "")
                {
                    oderby = order + " " + sort;
                }
                DataSet ds = bll.GetListByPage(strWhere.ToString(), oderby, (page - 1) * pageRows + 1, page * pageRows);
                int count = bll.GetRecordCount(strWhere.ToString());//获取条数  
                string strJson = ToJson.Dataset2Json(ds, count);//DataSet数据转化为Json数据  
                context.Response.Write(strJson);//返回给前台页面  
                context.Response.End();
            }

        }
        private string GetTreechild(DataTable tabel, string idCol, string rela, object pId)
        {
            rechild.Append(sb.ToString());
            sb.Remove(0, sb.Length);
            if (tabel.Rows.Count > 0)
            {
                string filer = string.Format("{0}='{1}'", rela, pId);
                DataRow[] rows = tabel.Select(filer);
                if (rows.Length > 0)
                {
                    foreach (DataRow row in rows)
                    {
                        sb.Append(row[idCol] + ",");
                        if (tabel.Select(string.Format("{0}='{1}'", rela, row[idCol])).Length > 0)
                        {
                            GetTreechild(tabel, idCol, rela, row[idCol]);
                            rechild.Append(sb.ToString());
                            sb.Remove(0, sb.Length);
                        }
                        rechild.Append(sb.ToString());
                        sb.Remove(0, sb.Length);
                    }
                    //sb = sb.Remove(sb.Length - 1, 1);
                }
                rechild.Append(sb.ToString());
                sb.Remove(0, sb.Length);
            }
            return rechild.ToString();
        }
        public void delete(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            int uid = 0;
            string uidstr = context.Request.QueryString["mid"];
            if (uidstr != "")
                uid = int.Parse(uidstr);
            if (bll.Delete(uid))
            {
                context.Response.Write("T");//返回给前台页面  
                context.Response.End();
            }
            else
            {
                context.Response.Write("F");//返回给前台页面  
                context.Response.End();

            }

        }
        public void modify(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            string province = Web.Admin.myinfo.getPCC(context).Split(',')[0];
            if (province != "")
            {
                int mlevel = 1;
                string mname = context.Request.Form["mname"];
                DateTime? mdatetime = null;
                string madd = context.Request.Form["madd"];
                string mmark = context.Request.Form["mmark"];
                decimal mjd = 0;
                decimal mwd = 0;
                string savepath = "";
                string hmpic = context.Request.Form["mpic"];
                HttpFileCollection files = context.Request.Files;
                if (files.Count == 1)
                {
                    HttpPostedFile file = files[0];
                    if (file.ContentLength > 0)
                    {
                        //全路径  
                        string FullFullName = file.FileName;
                        //获取图片的名称  
                        String fileName = FullFullName.Substring(FullFullName.LastIndexOf("\\") + 1);
                        string exp = fileName.Substring(fileName.LastIndexOf('.')).ToLower();
                        string filenames = DateTime.Now.ToString("yyyyMMddHHmmssfff");
                        string path = "~/mpics";
                        savepath = "/mpics";
                        if (exp == ".jpg" || exp == ".bmp" || exp == ".gif" || exp == ".png")
                        {
                            file.SaveAs(System.Web.HttpContext.Current.Server.MapPath(path) + "\\" + filenames + exp);
                            savepath += "/" + filenames + exp;
                        }
                        else
                        {
                            context.Response.Write("P");//返回给前台页面  
                            context.Response.End();

                        }
                    }
                    else
                    {
                        savepath = hmpic;

                    }
                }
                else
                {
                    savepath = hmpic;

                }
                int uid = 0;
                if (context.Request.Form["uid"] != "")
                    uid = int.Parse(context.Request.Form["uid"]);
                int mid = 0;
                if (context.Request.Form["mid"] != "")
                    mid = int.Parse(context.Request.Form["mid"]);
                if (context.Request.Form["mdatetime"] != "")
                    mdatetime = DateTime.Parse(context.Request.Form["mdatetime"]);
                if (context.Request.Form["mlevel"] != "")
                    mlevel = int.Parse(context.Request.Form["mlevel"]);
                if (context.Request.Form["mjd"] != "")
                    mjd = decimal.Parse(context.Request.Form["mjd"]);
                if (context.Request.Form["mwd"] != "")
                    mwd = decimal.Parse(context.Request.Form["mwd"]);
                cebao.Model.mapinfo model = new cebao.Model.mapinfo();
                model.mlevel = mlevel;
                model.uid = uid;
                model.mname = mname;
                model.madd = madd;
                model.mmark = mmark;
                model.mdatetime = mdatetime;
                model.mjd = mjd;
                model.mwd = mwd;
                model.mid = mid;
                model.mpic = savepath;
                if (bll.Update(model))
                {
                    context.Response.Write("T");//返回给前台页面  
                    context.Response.End();

                }
                else
                {
                    context.Response.Write("F");//返回给前台页面  
                    context.Response.End();
                }
            }
            else
            {
                context.Response.Write("L");//返回给前台页面  
                context.Response.End();
            }
        }
        public void add(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            if (Web.Admin.myinfo.isLogin(context))
            {
                string savepath = "";
                HttpFileCollection files = context.Request.Files;
                if (files.Count == 1)
                {
                    HttpPostedFile file = files[0];
                    if (file.ContentLength > 0)
                    {
                        //全路径  
                        string FullFullName = file.FileName;
                        //获取图片的名称  
                        String fileName = FullFullName.Substring(FullFullName.LastIndexOf("\\") + 1);
                        string exp = fileName.Substring(fileName.LastIndexOf('.')).ToLower();
                        string filenames = DateTime.Now.ToString("yyyyMMddHHmmssfff");
                        string path = "~/mpics";
                        savepath = "/mpics";
                        if (exp == ".jpg" || exp == ".bmp" || exp == ".gif" || exp == ".png")
                        {
                            file.SaveAs(System.Web.HttpContext.Current.Server.MapPath(path) + "\\" + filenames + exp);
                            savepath += "/" + filenames + exp;
                        }
                        else
                        {
                            context.Response.Write("P");//返回给前台页面  
                            context.Response.End();

                        }
                    }
                }
                int mlevel = 1;
                string mname = context.Request.Form["mname"];
                DateTime? mdatetime=null;
                string madd = context.Request.Form["madd"];
                string mmark = context.Request.Form["mmark"];
                decimal mjd = 0;
                decimal mwd = 0;
                int uid = 0;
                if (context.Request.Form["uid"] != "")
                    uid = int.Parse(context.Request.Form["uid"]);
                if (context.Request.Form["mdatetime"] != "")
                    mdatetime = DateTime.Parse(context.Request.Form["mdatetime"]);
                if (context.Request.Form["mlevel"] != "")
                    mlevel = int.Parse(context.Request.Form["mlevel"]);
                if (context.Request.Form["mjd"] != "")
                    mjd = decimal.Parse(context.Request.Form["mjd"]);
                if (context.Request.Form["mwd"] != "")
                    mwd = decimal.Parse(context.Request.Form["mwd"]);
                cebao.Model.mapinfo model = new cebao.Model.mapinfo();
                model.mlevel = mlevel;
                model.uid = uid;
                model.mname = mname;
                model.madd = madd;
                model.mmark = mmark;
                model.mdatetime = mdatetime;
                model.mjd = mjd;
                model.mwd = mwd;
                model.mpic = savepath;
                if (bll.Add(model) > 0)
                {
                    context.Response.Write("T");//返回给前台页面  
                    context.Response.End();
                }
                else
                {
                    context.Response.Write("F");//返回给前台页面  
                    context.Response.End();
                }
            }
            else
            {
                context.Response.Write("L");//返回给前台页面  
                context.Response.End();
            }

        }
        
        private string GetTreeJsonByTable(DataTable tabel, string idCol, string txtCol, string rela, object pId)
        {
            result.Append(sb.ToString());
            sb.Remove(0, sb.Length);
            if (tabel.Rows.Count > 0)
            {
                sb.Append("[");
                string filer = string.Format("{0}='{1}'", rela, pId);
                DataRow[] rows = tabel.Select(filer);
                if (rows.Length > 0)
                {
                    foreach (DataRow row in rows)
                    {
                        sb.Append("{\"id\":\"" + row[idCol] + "\",\"text\":\"" + row[txtCol] + "\",\"bm\":\"" + row["hbm"] + "\",\"ldxm\":\"" + row["ldxm"] + "\",\"rvalue\":\"" + row["rvalue"] + "\"");
                        if (tabel.Select(string.Format("{0}='{1}'", rela, row[idCol])).Length > 0)
                        {
                            //点击展开
                            sb.Append(",\"children\":");
                            GetTreeJsonByTable(tabel, idCol, txtCol, rela, row[idCol]);
                            result.Append(sb.ToString());
                            sb.Remove(0, sb.Length);
                        }
                        result.Append(sb.ToString());
                        sb.Remove(0, sb.Length); ;
                        sb.Append("},");
                    }
                    sb = sb.Remove(sb.Length - 1, 1);
                }
                sb.Append("]");
                result.Append(sb.ToString());
                sb.Remove(0, sb.Length);
            }
            return result.ToString();
        }
        private string GetTreeJsonByTableOne(DataTable tabel, string idCol, string txtCol, string bmCol)
        {
            result.Remove(0, result.Length);
            if (tabel.Rows.Count > 0)
            {
                result.Append("[");
                foreach (DataRow row in tabel.Rows)
                {
                    result.Append("{\"id\":\"" + row[idCol] + "\",\"text\":\"" + row[txtCol] + "\",\"bm\":\"" + row[bmCol] + "\"},");
                }
                result = result.Remove(result.Length - 1, 1);
                result.Append("]");
            }
            return result.ToString();
        }
        public void Query(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            if (Web.Admin.myinfo.isLogin(context))
            {
                //string pro = Web.Admin.myinfo.getPCC(context).Split(',')[0];

                //StringBuilder strWhere = new StringBuilder();
                //if (pro != "")
                //{
                //    strWhere.AppendFormat(" province='{0}'  ", pro);
                //}
                DataSet ds = bll.GetList(" 1=1 order by hbm");

                string str = GetTreeJsonByTable(ds.Tables[0], "hid", "hname", "parentid", 0);
                context.Response.Write(str);//返回给前台页面  
                context.Response.End();
            }
        }
        public void Querymy(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            if (Web.Admin.myinfo.isLogin(context))
            {
                cebao.BLL.mapinfo mybll = new BLL.mapinfo();
                int uid = 0;
                string uids = context.Request.Form["uid"];
                if (uids != "") uid = int.Parse(uids);
                DataSet ds = mybll.GetList(" uid=" + uid);
                //string str = GetTreeJsonByTableOne(ds.Tables[0], "mhid", "hname", "hbm");
                //context.Response.Write(str);//返回给前台页面  
                //context.Response.End();
                //DataSet ds = bll.GetListByPage(strWhere.ToString(), oderby, (page - 1) * pageRows + 1, page * pageRows);
                int count = ds.Tables[0].Rows.Count;//获取条数  
                string strJson = ToJson.Dataset2Json(ds, count);//DataSet数据转化为Json数据  
                context.Response.Write(strJson);//返回给前台页面  
                context.Response.End();
            }
        }
       
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}